<template>
  <q-page >
    <q-card flat square class="q-pa-none my-card back-dark">
      <q-card-section flat horizontal class="row items-center bg-grey-10">
        <q-breadcrumbs class="row items-center q-pl-sm text-body1">
          <q-breadcrumbs-el label="视频资源" icon="mdi-file-video-outline" @click="handleBack" />
          <q-breadcrumbs-el :label="folderInfo[0].vc_name" />
        </q-breadcrumbs>
        <q-space></q-space>
        <q-btn dense flat :ripple="{ center: true }" icon="mdi-sort" @click="refreshVideo">
          <q-tooltip>排序</q-tooltip>
        </q-btn>
        <q-btn dense flat :ripple="{ center: true }" icon="mdi-refresh" @click="refreshVideo">

          <q-tooltip>刷新项目数据</q-tooltip>

        </q-btn>
        <q-btn class="q-py-sm q-pr-sm q-ma-xs q-mr-md" dense flat :ripple="{ center: true }"
          icon="mdi-plus-box-multiple-outline">
          <q-badge class="q-mt-sm" color="orange" floating>{{taskNum}}</q-badge>
          <q-menu v-model="isUploadMenu" anchor="bottom end" self="top right">
            <q-card>
              <q-card-section class="q-py-sm no-shadow">
                <q-btn dense icon="ti-cloud-up" class="q-my-sm q-mr-sm" size="12px" color="primary" label="上传"
                  @click="handleUploadVideo"></q-btn>
                <!-- <q-btn dense icon="ti-folder" class="q-my-sm q-mr-sm" size="12px" color="primary" label="新建"
                  @click="handleCreateFolderPop"></q-btn> -->
              </q-card-section>
              <q-card-section class="q-pa-none no-shadow">
                <q-table title="任务列表" :data="data" :columns="columns" row-key="name">
                  <template v-slot:no-data="{noDataMsg}">
                    <div class="full-width row flex-center text-grey-10 q-gutter-sm">
                      <q-icon size="2em" name="ti-package" />
                      <span>
                        暂时没有上传任务{{ noDataMsg }}
                      </span>
                      <q-icon size="2em" :name="filter ? 'filter_b_and_w' : icon" />
                    </div>
                  </template>
                  <template v-slot:body="props">
                    <q-tr :props="props">
                      <q-td key="name" :props="props">
                        {{ props.row.name }}
                      </q-td>
                      <q-td key="fileSize" :props="props">
                        {{ props.row.fileSize }}
                      </q-td>
                      <q-td key="process" :props="props">
                        <q-linear-progress stripe rounded size="25px" style="min-width:100px"
                          :value="props.row.process/100" color="accent">
                          <div class="absolute-full flex flex-center">
                            <q-badge color="white" text-color="accent"
                              :label="props.row.isUploaded?props.row.process+'%':props.row.statusMsg" />
                          </div>
                        </q-linear-progress>
                      </q-td>
                      <q-td key="status" :props="props">
                        <div v-if="props.row.status=='0'">
                          <q-badge color="yellow-10">
                            待开始
                          </q-badge>

                        </div>
                        <div v-if="props.row.status=='1'">
                          <q-badge color="blue-10">
                            上传中
                          </q-badge>

                        </div>

                        <q-badge v-if="props.row.status=='2'" color="green-6">
                          已完成
                        </q-badge>
                        <div v-if="props.row.status=='3'">
                          <q-badge color="red-6">
                            失&emsp;败
                          </q-badge>
                        </div>

                      </q-td>
                      <q-td key="action" :props="props">

                        <div v-if="props.row.status=='0'">
                          <q-btn icon="mdi-delete-forever-outline" outline size="12px" color="red-6" dense>
                            <q-tooltip>删除任务</q-tooltip>
                          </q-btn>

                        </div>

                        <div v-if="props.row.status=='2' || props.row.status=='1' ">
                          <q-btn icon="mdi-minus-circle-outline" outline size="12px" color="green-6" dense>
                            <q-tooltip>移除任务</q-tooltip>
                          </q-btn>
                        </div>

                        <div v-if="props.row.status=='3'">
                          <q-btn icon="mdi-restart" outline size="12px" color="yellow-10" dense>
                            <q-tooltip>重新上传</q-tooltip>
                          </q-btn>
                        </div>

                      </q-td>

                    </q-tr>
                  </template>
                </q-table>
              </q-card-section>


            </q-card>

          </q-menu>


        </q-btn>
      </q-card-section>
    </q-card>

    <div v-show="isLoadData" class="column items-center justify-center" :style="
      $q.platform.is.mobile
        ? 'position:fixed;left:0;top:100px;right:0;bottom:0'
        : 'position:absolute;left:0;right:0;top:50px;bottom:0px'
    ">
      <q-spinner-hourglass color="primary" size="5em" />
      数据加载中，请稍等……
    </div>
    <q-scroll-area v-show="!isLoadData" :visible="false" :thumb-style="{
      right: '4px',
      borderRadius: '5px',
      backgroundColor: '#009688',
      width: '5px',
      opacity: 0.75,
    }" :bar-style="{
      right: '2px',
      borderRadius: '9px',
      backgroundColor: '#03a9f4',
      width: '9px',
      opacity: 0.2,
    }" :style="
      $q.platform.is.mobile
        ? 'position:fixed;left:0;top:100px;right:0;bottom:0'
        : 'position:absolute;left:0;right:0;top:50px;bottom:0px'
    ">
      <q-card flat square bordered class="q-pa-none my-card back-dark">
        <div class="row wrap items-evenly  q-pa-md q-gutter-md" ref="videoContainer">
          <q-responsive v-for="(item, index) in folderList" :key="index" :ratio="16 / 14" class="col transparent"
            style="min-width:180px; min-height: 180px;">
            <q-card @dragenter="dragenter($event)" @dragover="dragover($event)"
              @drop="handleFileDrop($event, item.pv_id)" flat class="transparent">
              <q-responsive :ratio="16 / 14" :ref="item.pv_id"
                style="background-image: url(icons/studio/folder.svg);background-repeat: no-repeat;">
                <q-card-section class="q-pa-none">
                  <q-responsive :ratio="16 / 8" @click="handleEnterFolder(item)">
                    <div class="column wrap q-pa-sm justify-center">

                    </div>
                  </q-responsive>
                  <q-responsive :ratio="16 / 6">
                    <div class="column wrap q-pa-sm justify-center">
                      <div style="width: 100%" class="col-5 ellipsis" :title="item.vc_name">
                        {{ item.vc_name }}
                      </div>
                      <div class="row col-7 items-center justify-between">
                        <div class="row no-wrap items-center">
                          <q-avatar class="q-mr-sm" size="20px">
                            <img :src="item.avatar" alt="创建者" />
                          </q-avatar>
                          <div class=" tipsfont column" style="font-size:10px">
                            <div style="font-size:10px">
                              {{ item.vc_ctime }}
                            </div>

                          </div>
                        </div>

                        <div class="">
                          <i class="q-mr-xs fas fa-ellipsis-v" color="grey-1"></i>
                          <q-menu>
                            <q-list dense style="min-width: 100px">
                              <q-item clickable v-close-popup>
                                <q-item-section @click="handleshare(item)">
                                  <div class="row items-center">
                                    <q-icon class="q-mr-sm" name="mdi-share-outline" />
                                    分享
                                  </div>
                                </q-item-section>
                              </q-item>
                              <q-item clickable v-close-popup>
                                <q-item-section @click="handleRenameFolder(item)">
                                  <div class="row items-center">
                                    <q-icon class="q-mr-sm" name="mdi-rename-box" />
                                    重命名
                                  </div>
                                </q-item-section>
                              </q-item>
                              <q-separator />
                              <q-item clickable v-close-popup>
                                <q-item-section @click="handleDeleteFolder(item)">
                                  <div class="row items-center">
                                    <q-icon class="q-mr-sm" name="mdi-trash-can-outline" />
                                    删除
                                  </div>
                                </q-item-section>
                              </q-item>
                            </q-list>
                          </q-menu>
                        </div>
                      </div>
                    </div>
                  </q-responsive>

                </q-card-section>
              </q-responsive>

            </q-card>
          </q-responsive>
          <div :style="blockStyle"></div>
          <div :style="blockStyle"></div>
          <div :style="blockStyle"></div>
          <div :style="blockStyle"></div>
          <div :style="blockStyle"></div>
          <div :style="blockStyle"></div>
          <div :style="blockStyle"></div>
          <div :style="blockStyle"></div>
          <div :style="blockStyle"></div>
          <div :style="blockStyle"></div>
        </div>
      </q-card>

      <q-card flat square bordered class="q-pa-none my-card back-dark">
        <div class="row wrap items-evenly  q-pa-md q-gutter-md" ref="videoContainer">
          <q-responsive v-for="(item, index) in filelists" :key="index" :ratio="1" class="col" ref="videoCard"
            style="min-width:180px; min-height: 180px">
            <q-card draggable="true" class="my-card bg-grey-10" @dragstart="drag($event, item.work_id)">
              <q-responsive @click="handlevideo(item)" :ratio="16 / 9" :ref="item.work_id">
                <q-card-section @mousemove="handlepreview($event, item, index)"
                  @mouseout="handlemouseout($event, item, index)" class="q-pa-none" :style="item.backimg">
                  <q-badge class="q-ma-sm q-pa-xs bg-tm" align="middle">version: {{ item.version }}.0
                  </q-badge>
                  <q-badge align="middle" v-show="!item.isprogressshow" class="q-ma-sm q-pa-xs bg-tm"
                    style="position: absolute; bottom: 5px; left: 0">{{ item.videoinfo.format.duration
                    }}</q-badge>
                  <q-badge v-show="!item.isprogressshow" v-if="item.status == 0" align="middle" class="q-ma-sm q-pa-xs"
                    style="position: absolute; bottom: 5px; right: 0" outline color="yellow-6">正在转码</q-badge>
                  <q-badge v-show="!item.isprogressshow" v-if="item.status == 1" align="middle" class="q-ma-sm q-pa-xs"
                    style="position: absolute; bottom: 5px; right: 0" outline color="yellow-6">待审核</q-badge>
                  <q-badge v-show="!item.isprogressshow" v-if="item.status == 2" align="middle" class="q-ma-sm q-pa-xs"
                    style="position: absolute; bottom: 5px; right: 0" outline color="yellow-6">审核中</q-badge>
                  <q-badge v-show="!item.isprogressshow" v-if="item.status == 3" align="middle" class="q-ma-sm q-pa-xs"
                    style="position: absolute; bottom: 5px; right: 0" outline color="yellow-6">审核完成</q-badge>
                  <q-linear-progress v-if="item.isprogressshow" :value="item.progress"
                    style="position: absolute; bottom: 0" class="shadow-7" size="md" track-color="grey-8"
                    color="teal-11" />
                </q-card-section>
              </q-responsive>
              <q-responsive :ratio="16 / 7">
                <div class="column wrap q-pa-sm justify-center">
                  <div style="width: 100%" class="col-5 ellipsis" :title="item.name">
                    {{ item.name }}
                  </div>
                  <div class="row col-7 items-center justify-between">
                    <div class="row no-wrap items-center">
                      <q-avatar class="q-mr-sm" size="20px">
                        <img :src="item.avatar" alt="创建者" />
                      </q-avatar>
                      <div class=" tipsfont column" style="font-size:10px">
                        <div style="font-size:10px">
                          {{ item.ctime }}
                        </div>
                        <div style="font-size:10px">
                          {{ item.videoinfo.format.size }}

                          <i class="q-mx-sm fas fa-comments"></i>
                          {{ item.count ? item.count : "0" }}
                        </div>
                      </div>
                    </div>

                    <div class="">
                      <i class="q-mr-xs fas fa-ellipsis-v" color="grey-1"></i>
                      <q-menu>
                        <q-list dense style="min-width: 100px">
                          <q-item clickable v-close-popup>
                            <q-item-section @click="handleshare(item)">
                              <div class="row items-center">
                                <q-icon class="q-mr-sm" name="mdi-share-outline" />
                                分享
                              </div>
                            </q-item-section>
                          </q-item>
                          <q-item clickable v-close-popup>
                            <q-item-section @click="handlerename(item)">
                              <div class="row items-center">
                                <q-icon class="q-mr-sm" name="mdi-rename-box" />
                                重命名
                              </div>
                            </q-item-section>
                          </q-item>
                          <q-separator />
                          <q-item clickable v-close-popup>
                            <q-item-section @click="handledelete(item)">
                              <div class="row items-center">
                                <q-icon class="q-mr-sm" name="mdi-trash-can-outline" />
                                删除
                              </div>
                            </q-item-section>
                          </q-item>
                        </q-list>
                      </q-menu>
                    </div>
                  </div>
                </div>
              </q-responsive>
            </q-card>
          </q-responsive>
          <div :style="blockStyle"></div>
          <div :style="blockStyle"></div>
          <div :style="blockStyle"></div>
          <div :style="blockStyle"></div>
          <div :style="blockStyle"></div>
          <div :style="blockStyle"></div>
          <div :style="blockStyle"></div>
          <div :style="blockStyle"></div>
          <div :style="blockStyle"></div>
          <div :style="blockStyle"></div>
          <div :style="blockStyle"></div>
          <div :style="blockStyle"></div>
          <div :style="blockStyle"></div>
        </div>
        <q-card-section class="q-pt-none"> </q-card-section>
      </q-card>

      <q-dialog v-model="isrename" persistent>
        <q-card>
          <q-card-section class="row items-center">
            <div class="column">
              <div class="text-h6">重命名</div>
              <div class="q-my-sm">当前作品名称：{{ curvideo.name }}</div>
              <q-input v-model="curvideo.newname" label="新名称" />
            </div>
          </q-card-section>

          <q-card-actions align="right">
            <q-btn flat label="取消" color="primary" v-close-popup />
            <q-btn flat label="确认" color="primary" @click="confirmrename" />
          </q-card-actions>
        </q-card>
      </q-dialog>
      <q-dialog v-model="isCreateFolder" persistent>
        <q-card>
          <q-card-section class="row items-center">
            <div class="column">
              <div class="text-body1">新建文件夹</div>
              <q-input v-model="folderName" label="文件夹名称" />
            </div>
          </q-card-section>

          <q-card-actions align="right">
            <q-btn flat label="取消" color="primary" v-close-popup />
            <q-btn flat label="确认" color="primary" @click="createFolder" />
          </q-card-actions>
        </q-card>
      </q-dialog>
      <q-dialog v-model="isRenameFolder" persistent>
        <q-card>
          <q-card-section class="row items-center">
            <div class="column">
              <div class="text-h6">重命名</div>
              <div class="q-my-sm">当前文件夹名称：{{ curFolder.name }}</div>
              <q-input v-model="curFolder.newName" label="新名称" />
            </div>
          </q-card-section>

          <q-card-actions align="right">
            <q-btn flat label="取消" color="primary" v-close-popup />
            <q-btn flat label="确认" color="primary" @click="confirmRenameFolder" />
          </q-card-actions>
        </q-card>
      </q-dialog>
      <q-dialog v-model="isUpload" persistent>
        <q-card>
          <q-card-section class="row items-center">
            <div class="column">
              <div class="text-body1 q-mb-md">上传视频</div>
              <el-upload ref="upload" class="upload-demo" drag :multiple="true" :action="uploadurl" accept=".mov,.mp4"
                :auto-upload="false" :on-change="handleChange" :headers="uploadheaders" :on-remove="handleremovefile">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">上传文件类型：mov、mp4视频文件</div>
              </el-upload>

            </div>
          </q-card-section>

          <q-card-actions align="right">
            <q-btn outline label="上传文件" color="primary" @click="submitUpload" />
            <q-btn outline label="取消" color="primary" v-close-popup />

          </q-card-actions>
        </q-card>
      </q-dialog>

    </q-scroll-area>
  </q-page>
</template>

<script>
import { copyToClipboard } from "quasar";
import { deleteVideo, videoRename, createFolder, loadFolderList, moveFile, renameFolder,loadFolderInfo,loadFolderVideo } from "assets/api/studio";
import { date } from "quasar";
import storage from "assets/utils/storage";
import { loadfilelist } from "assets/api/studio";
import { getSeconds } from "assets/utils/stodate";
import SparkMD5 from "spark-md5";
import { fileParse } from "assets/utils/fileparse";
import {
  uploadvideo,
  mergeVideo,
  searchMD5,
  checkuploadfile,
} from "assets/api/work";

export default {
  data() {
    return {
      isLoadData: true,
      taskNum: 0,
      isUploadMenu: false,
      noDataMsg: '',
      columns: [
        {
          name: 'name',
          required: true,
          label: '文件名',
          align: 'left',
          field: row => row.name,

        },
        {
          name: 'fileSize',
          required: true,
          label: '大小',
          align: 'center',
          field: row => row.fileSize,

        },
        { name: 'process', align: 'center', label: '进度', field: row => row.process },
        { name: 'status', label: '状态', field: row => row.status, sortable: true },
        { name: 'action', label: '操作', field: row => row.status, sortable: true },
      ],
      data: [
      ],
      pid: "",
      isrename: false,
      curvideo: {},
      uploadheaders: [],
      formfields: [],
      backimg: {
        backgroundImage:
          "url(http://121.196.19.223:3000/upload/studio/video/YFYH2101042323/202101304130/newthumb/thumb.jpg)",
        backgroundPosition: " 0px 0px",
        backgroundSize: "auto 100%",
      },
      imgInfo: {},
      isprogressshow: false,
      progress: 0,
      filelists: [],
      blockStyle: {
        "min-width": "180px",
        " min-height": "180px",

        "margin-top": "0px !important"
      },
      isCreateFolder: false,
      folderName: "新建文件夹",
      folderList: [],
      curDraggedWorkId: '',
      isRenameFolder: false,
      curFolder: {
        name: '',
        newName: ''
      },

        folderInfo:'',
      isUpload: false,
      uploadurl: '',
      fileList: [],
      uploadheaders: {},
      uploadres: [],
      isupload: false,

    };
  },
  created() {
    this.pid = this.$route.params.pid;
    this.pv_id = this.$route.params.pv_id;
    console.log(this.pv_id);
    this.$store.commit("setselecttab", "videos");
  },
  mounted() {
    this.loadFolderInfo();
    this.loadfilelists();
    let user = storage.getItem("user");
    this.uploadheaders = {
      name: "Authorization",
      value: user.token,
    };
    this.formfields.push({
      name: "pid",
      value: this.pid,
    });
    window.onresize = () => {
      this.handleVideoCard()
    };
    setTimeout(() => {
      this.handleVideoCard();

    }, 100)

  },
  beforeDestroy() {
    this.$store.commit("setselecttab", "projects");
  },
  methods: {
    handleBack(){

      this.$router.go(-1)
    },
    loadFolderInfo() {
        loadFolderInfo({
          pv_id: this.pv_id
        }).then((res) => {
          if (res.data.code == 1) {
            let data = res.data.data;

              data.vc_ctime = date.formatDate(data.vc_ctime, "YYYY-MM-DD HH:mm");
              data.vc_lastModifyTime = date.formatDate(data.vc_lastModifyTime, "YYYY-MM-DD HH:mm");

            this.folderInfo = data
            console.log(this.folderInfo);
          }

        })
      },
    reloadUploadMenu() {
      this.isUploadMenu = false;
      setTimeout(() => {
        this.isUploadMenu = true;
      }, 200)

    },
    async ParseFile(file) {
      let buffer = await fileParse(file, "buffer");
      return buffer
    },
    testQueue() {
      let fileList = this.data;
      let fileNum = 0
      fileList.forEach(v => {
        if (v.status == 1) {
          fileNum += 1
        }
      })
      if (fileNum <= 2) {
        this.uploadTask()
      }

    },
    uploadTask() {
      let fileNum = 0;
      let fileList = this.data;
      console.log('文件列表', fileList);
      let taskNum = 0;
      fileList.forEach(v => {
        if (v.status < 2) {
          taskNum += 1;
        }
      });
      this.taskNum = taskNum;
      for (let index = 0; index <= fileList.length - 1; index++) {
        let v = fileList[index];
        console.log('数据', v);
        if (v.status == 0 && fileNum < 1) {
          console.log('开始上传');
          v.statusMsg = "文件解析中……";
          v.status = 1;
          v.isupload = false;
          v.isload = true;
          v.fileList = fileList;
          let file = v.file;
          v.rawfilename = file.name;

          this.ParseFile(file).then(buffer => {
            v.statusMsg = "切片中……";
            let spark = new SparkMD5.ArrayBuffer(),
              hash,
              suffix;
            spark.append(buffer);
            hash = spark.end();
            suffix = /\.([0-9a-zA-Z]+)$/i.exec(file.name)[1];
            // 每个文件2Mb来切片
            let chunksize = 2 * 1024 * 1024;
            let total = Math.ceil(file.size / chunksize);
            v.total = total;
            let partList = [],
              cur = 0;
            for (let i = 0; i < v.total; i++) {
              let item = {
                chunk: file.slice(cur, cur + chunksize),
                filename: `${hash}_${i}.${suffix}`,
              };
              cur += chunksize;
              partList.push(item);
            }
            v.statusMsg = "解析完成";
            v.partList = partList;
            v.hash = hash;
            this.verifymd5(v)

          })

          fileNum = fileNum + 1;
          console.log('正在上传的文件数', fileNum);

        }
      }
    },
    uploadSuccess(v) {
      v.status = 2;
      v.statusMsg = '上传成功！';
      this.testQueue();
      let num = 0;
      let fileList = this.data;
      fileList.forEach(v => {
        if (v.status == 2) {
          num += 1
        }
      });
      if (num == fileList.length) {
        this.handlesuccess()
      }
    },

    submitUpload() {
      if (this.fileList.length > 0) {
        if (this.isupload) {
          let fileList = this.fileList;
          fileList.forEach((v, i) => {
            this.data.push(
              {
                name: v.name,
                process: 0,
                status: 0,
                fileSize: (v.size / 1024 / 1024).toFixed(2) + "MB",
                statusMsg: '上传队列中……',
                isUploaded: false,
                file: v.raw,
                fileList: [],
                uploadres: [],
                partList: [],
                hash: "",
                rawfilename: "",
                total: 0,
                isupload: false,
                curchunk: 0,
                check: 0,
                checkedPartlist: [],
                leftPartlist: [],
                pid: this.pid
              }

            );
            this.isUpload = false;
            this.reloadUploadMenu();
            this.fileList = [];


          })
          setTimeout(() => {
            this.uploadTask();

          }, 500)


          // this.isload = true;
          // this.verifymd5();
        }
      } else {
        this.$message.error("请先选择要上传的文件！");
      }
    },
    async handleChange(file, fileList) {
      console.log(fileList);
      this.fileList = fileList;
      this.isupload = true;

    },
    //文件校验

    async verifymd5(v) {
      v.statusMsg = "检查缓存……";
      let data = {
        md5: v.hash,
      };
      //检查是否数据库存在相同文件
      searchMD5(data).then((res) => {
        let data = res.data.data;
        if (data.length > 0) {
          this.uploadSuccess(v)
          return
        }
        //检查本地缓存是否有上传过的分片文件
        var checklist = [];
        v.partList.map((item, index) => {
          let fn = () => {
            let filedata = {
              hash: v.hash,
              filename: item.filename,
            };

            checkuploadfile(filedata).then((res) => {
              let data = res.data;
              if (data.code == 11) {
                v.curchunk += 1;
              }
              //将没有上传的分片文件push到新的文件数组
              v.check += 1;
              if (data.code == 10) {
                v.checkedPartlist.push(item);
              }
              v.process = parseFloat(((this.curchunk / this.total) * 100).toFixed(2))
              if (v.check == v.total) {
                v.statusMsg = "检查缓存完成";
                this.sendRequest(v)

              }
            });
          };
          checklist.push(fn);
        });
        var i = 0;
        let send = async () => {
          if (i >= checklist.length) {
            return;
          }
          await checklist[i]();
          i++;

          send();

        };
        send()
      });
    },
    //发送文件上传请求
    async sendRequest(v) {
      // 根据100个切片创造100个请求（集合）
      //开始真正上传，将checklist里没有上传的分片文件上传
      v.isUploaded = true;
      //分片文件已经全部上传完毕
      if (v.curchunk == v.total) {
        let complete = async () => {
          let data = {
            hash: v.hash,
            rawfilename: v.rawfilename,
            pid: this.pid
          };
          await mergeVideo(data);
        };

        complete().then(res => {
          console.log("长传这儿", res);
          this.uploadSuccess(v)
          return

        });

      }
      //上传剩余分片文件
      let requestList = [];
      v.checkedPartlist.map((item, index) => {
        // 每一个函数都是发送一个切片的请求
        let fn = () => {
          let formData = new FormData();
          formData.append("chunk", item.chunk);
          formData.append("hash", v.hash);
          formData.append("filename", item.filename);
          uploadvideo(formData).then((res) => {
            res = res.data;
            if (res.code == 1) {
              v.curchunk += 1;
              // 传完的切片我们把它移除掉
              if (v.curchunk == v.total) {
                complete().then(res => {
                  console.log("上传完毕这儿", res);
                  this.uploadSuccess(v)
                  return;
                });

              }
            } else {
              v.leftPartlist.push(item);
            }
            v.process = parseFloat(((v.curchunk / v.total) * 100).toFixed(2))
          });
        };
        requestList.push(fn);
      });

      // 传递：并行(ajax.abort())/串行(基于标志控制不发送)
      var i = 0;
      let complete = async () => {
        let data = {
          hash: v.hash,
          rawfilename: v.rawfilename,
          pid: this.pid
        };
        await mergeVideo(data);
      };
      let send = async () => {
        // 已经中断则不再上传
        // if (this.abort) return;
        if (i >= requestList.length) {
          return;
        }
        await requestList[i]();
        i++;
        send();
      };
      send();
    },
    handlesuccess() {
      this.$message.success("上传完了！");
      this.loadFolderList()
      this.loadfilelists();
    },
    refreshVideo() {
      this.isLoadData = true;
      this.loadFolderList()
      this.loadfilelists();

    },
    handleremovefile(file, filelist) {
      console.log("移除文件");
    },
    handleUploadVideo() {
      this.isUpload = true
    },
    handleEnterFolder(item) {
      this.$router.push({ name: "studioVideoFile", params: { pv_id: item.pv_id } })
    },
    reloadFile() {
      this.loadFolderList();
      this.loadfilelists();
    },
    dragover(e) {
      e.preventDefault()
    },
    dragenter(e) {
      console.log(e);
    },
    drag(e, id) {
      console.log(e);
      this.curDraggedWorkId = id;
    },
    handleFileDrop(e, pv_id) {
      console.log("拖放文件", this.curDraggedWorkId, pv_id);
      moveFile({
        work_id: this.curDraggedWorkId,
        pv_id
      }).then((res) => {
        if (res.data.code == 1) {
          this.$q.notify({
            color: "light-green-4",
            icon: "far fa-check-circle",
            position: "top",
            textColor: "white",
            message: "文件移动成功！",
            timeout: "1500",
          });
          this.reloadFile()
        } else {
          this.$q.notify({
            color: "red-5",
            textColor: "white",
            icon: "warning",
            position: "top",
            timeout: "1500",
            message: "文件移动失败！",
          });
        }
      })
    },
    handleRenameFolder(item) {
      this.isRenameFolder = true;
      this.curFolder.name = item.vc_name;
      this.curFolder.pv_id = item.pv_id;
    },
    confirmRenameFolder() {
      renameFolder({
        pv_id: this.curFolder.pv_id,
        newName: this.curFolder.newName
      }).then(res => {
        if (res.data.code == 1) {
          this.isCreateFolder = false;
          this.$q.notify({
            color: "light-green-4",
            icon: "far fa-check-circle",
            position: "top",
            textColor: "white",
            message: "重命名文件夹成功！",
            timeout: "1500",
          });
          this.isRenameFolder = false;
          this.reloadFile()

        } else {
          this.$q.notify({
            color: "red-5",
            textColor: "white",
            icon: "warning",
            position: "top",
            timeout: "1500",
            message: "重命名文件夹失败！",
          });
        }
      })
    },
    handleDeleteFolder() {

    },
    handleCreateFolderPop() {
      this.isCreateFolder = true

    },
    createFolder() {
      let data = {
        vc_name: this.folderName,
        pid: this.pid,
        vc_parentId: 0
      };
      createFolder(data).then(res => {
        if (res.data.code == 1) {
          this.isCreateFolder = false;
          this.$q.notify({
            color: "light-green-4",
            icon: "far fa-check-circle",
            position: "top",
            textColor: "white",
            message: "新建文件夹成功！",
            timeout: "1500",
          });
          this.loadFolderList()

        } else {
          this.$q.notify({
            color: "red-5",
            textColor: "white",
            icon: "warning",
            position: "top",
            timeout: "1500",
            message: "新建文件夹失败！",
          });
        }

      }).catch(err => {

      })

    },
    loadFolderList() {
      loadFolderList({
        pid: this.pid
      }).then((res) => {
        if (res.data.code == 1) {
          let data = res.data.data;
          data.forEach((item, index) => {
            item.vc_ctime = date.formatDate(item.vc_ctime, "YYYY-MM-DD HH:mm");
            item.vc_lastModifyTime = date.formatDate(item.vc_lastModifyTime, "YYYY-MM-DD HH:mm");
          })
          this.folderList = data
        }

      })
    },
    handleVideoCard() {
      if(this.$refs["videoContainer"].clientWidth && this.filelists.length>0){
        console.log("card宽", this.$refs["videoContainer"].clientWidth, this.$refs[this.filelists[0].work_id][0].$el.clientWidth);
      this.blockStyle.width = parseInt(this.$refs[this.filelists[0].work_id][0].$el.clientWidth) + "px";
      }


    },
    handleshare(item) {
      var vm = this;
      let url = this.GLOBAL.appurl + "/file/" + item.work_id;
      copyToClipboard(url)
        .then(() => {
          vm.$q.notify({
            position: "center",
            message: "复制链接成功！",
            timeout: 1000,
            color: "light-green-4",
            icon: "far fa-check-circle",
            textColor: "white",
          });
        })
        .catch(() => {
          // 失败
          vm.$q.notify({
            color: "red-5",
            textColor: "white",
            icon: "warning",
            position: "center",
            message: "复制失败！",
            timeout: 1000,
          });
        });
    },
    confirmrename() {
      if (!this.curvideo.newname) {
        this.$q.notify({
          color: "red-5",
          textColor: "white",
          icon: "warning",
          position: "top",
          timeout: "1500",
          message: "请先输入作品新名称！",
        });
        return;
      }
      let reqdata = {
        data: this.curvideo,
      };
      videoRename(reqdata).then((res) => {
        if (res.data.code == 1) {
          this.isrename = false;
          this.$q.notify({
            color: "light-green-4",
            icon: "far fa-check-circle",
            position: "top",
            textColor: "white",
            message: "重命名成功！",
            timeout: "1500",
          });
          this.loadfilelists();
        } else {
          this.$q.notify({
            color: "red-5",
            textColor: "white",
            icon: "warning",
            position: "top",
            timeout: "1500",
            message: "重命名失败！",
          });
        }
      });
    },
    handlerename(item) {
      this.isrename = true;
      this.curvideo.work_id = item.work_id;
      this.curvideo.name = item.name;
    },
    handledelete(item) {
      this.$q
        .dialog({
          title: "提示",
          message: "确认删除视频吗？",
          cancel: true,
          persistent: true,
        })
        .onOk(() => {
          let reqdata = {
            work_id: item.work_id,
          };
          deleteVideo(reqdata)
            .then((res) => {
              if (res.data.code == 1) {
                this.$q.notify({
                  color: "light-green-4",
                  icon: "far fa-check-circle",
                  position: "top",
                  textColor: "white",
                  message: "删除视频成功！",
                  timeout: "1500",
                });
                this.loadfilelists();
              } else {
                this.$q.notify({
                  color: "red-5",
                  textColor: "white",
                  icon: "warning",
                  position: "top",
                  message: "删除失败！",
                });
              }
            })
            .catch(() => {
              this.$q.notify({
                color: "red-5",
                textColor: "white",
                icon: "warning",
                position: "top",
                message: "删除失败！",
              });
            });
        })
        .onOk(() => {
          // console.log('>>>> second OK catcher')
        })
        .onCancel(() => {
          // console.log('>>>> Cancel')
        })
        .onDismiss(() => {
          // console.log('I am triggered on both OK and Cancel')
        });
    },
    handlevideo(item) {
      console.log(item);
      if (!item.m3u8url) {
        this.$q.notify({
          color: "red-5",
          textColor: "white",
          icon: "warning",
          position: "top",
          timeout: "1500",
          message: "作品转码中，稍后刷新重试！",
        });
      } else if (item.m3u8url) {
        this.$router.push("/file/" + item.work_id);
      }
    },
    loadfilelists() {
        let serveurl = this.GLOBAL.serveurl;
        let reqdata = {
          pv_id: this.pv_id,
        };
        loadFolderVideo(reqdata).then((res) => {
          this.isLoadData=false;
            console.log(res);
          let filelistdata = res.data.data;
          console.log(filelistdata);
          let newFilelist = []
          if (filelistdata.length > 0) {
            filelistdata.forEach((item, index) => {

                let ctime = date.formatDate(item.ctime, "YYMMDD");
                if (!item.name) {
                  item.name = ctime + "-" + storage.getItem(this.pid).name;
                }
                item.version = index + 1;
                item.ctime = date.formatDate(item.ctime, "YYYY-MM-DD HH:mm");
                item.videoinfo = JSON.parse(item.videoinfo);
                let duration = item.videoinfo.format.duration;
                let bitrate = item.videoinfo.format.bit_rate;
                let newbitrate =
                  Math.floor((bitrate / 1024 / 1024) * 100) / 100 + "mbps";
                let size = item.videoinfo.format.size;
                let newsize = Math.floor((size / 1024 / 1024) * 100) / 100 + "MB";
                let newduration = getSeconds(duration);
                item.videoinfo.format.duration = newduration;
                item.videoinfo.format.bit_rate = newbitrate;
                item.videoinfo.format.size = newsize;

                if (!item.thumbnail) {
                  let backimg = {
                    backgroundImage: "url(" + serveurl + "/upload/preview.jpg)",
                    backgroundPosition: " 0px 0px",
                    backgroundSize: "auto 100%",
                  };
                  item.backimg = backimg;
                } else if (item.thumbnail) {
                  let backimg = {
                    backgroundImage: "url(" + serveurl + item.thumbnail + ")",
                    backgroundPosition: " 0px 0px",
                    backgroundSize: "auto 100%",
                  };
                  item.backimg = backimg;
                }
                newFilelist.push(item)



            });
            this.filelists = newFilelist;


          }else{

          }
        });
      },

    handlestart() { },
    handleuploaded(info) {
      let res = JSON.parse(info.xhr.response);
      console.log(res);
      if (res.code == 1) {
        this.$q.notify({
          color: "light-green-4",
          icon: "far fa-check-circle",
          position: "top",
          textColor: "white",
          message: "上传成功！",
          timeout: "1500",
        });
        this.loadfilelists();
      }
    },
    handlepreview(evt, item, index) {
      if (this.$q.platform.is.desktop) {
        item.isprogressshow = true;
        let x = evt.layerX;
        let containerwidth = this.$refs[item.work_id][0].$el.clientWidth;
        let curposition = Math.floor((x / containerwidth) * 100);
        let img = new Image();
        img.src = item.backimg.backgroundImage
          .replace("url(", "")
          .replace(")", "");
        const vm = this;
        img.onload = function () {
          vm.$set(vm.imgInfo, "width", img.width);
          vm.$set(vm.imgInfo, "height", img.height);
        };
        let imgs = this.imgInfo.width / 320;
        let percent = parseInt(100 / imgs);

        let curimg = Math.floor(curposition / percent);
        item.progress = Math.ceil(curimg * percent + 5) / 100;
        let offsetimg = curimg - 1;
        item.backimg.backgroundPosition =
          "-" + offsetimg * containerwidth + "px 0px";
      }
    },
    handlemouseout(evt, item) {
      if (this.$q.platform.is.desktop) {
        item.isprogressshow = false;
        item.backimg.backgroundPosition = "0px 0px";
      }
    },
    getImgInfo() { },
  },
};
</script>
<style lang="scss">
.tipsfont {
  font-size: 12px;
  color: grey;
}

.bg-tm {
  background-color: rgba(82, 82, 82, 0.7);
}

.el-upload-dragger {
  min-width: 200px;
  max-width: 350px;
}
</style>
